﻿(function () {
    $(function () {
        var _$table = $('#tb');
        var _planService = abp.services.app.plan;

        var _permissions = {
            create: abp.auth.hasPermission("Pages.Plan.Plans.Create"),
            edit: abp.auth.hasPermission("Pages.Plan.Plans.Edit"),
            'delete': abp.auth.hasPermission("Pages.Plan.Plans.Delete")
        };

        var _createOrEditModal = new app.ModalManager({
            viewUrl: abp.appPath + 'Plans/CreateOrEditPlanModal',
            scriptUrl: abp.appPath + 'Views/Plans/_CreateOrEditPlanModal.js',
            modalClass: 'CreateOrEditPlanModal'
        });

       
        var TableInit = function () {

            var oTableInit = new Object();
            oTableInit.Init = function () {
                _$table.bootstrapTable({
                    url: '/Plans/GetAllPlans', //请求后台的URL（*）
                    //dataType: "json",  
                    contentType: "application/x-www-form-urlencoded",
                    //contentType: "application/json",
                    method: 'post', //请求方式（*）
                    toolbar: '#toolbar', //工具按钮用哪个容器
                    striped: true, //是否显示行间隔色
                    cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true, //是否显示分页（*）
                    sortable: true, //是否启用排序
                    sortOrder: "asc", //排序方式
                    queryParams: oTableInit.queryParams, //传递参数（*）
                    sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1, //初始化加载第一页，默认第一页
                    pageSize: 10, //每页的记录行数（*）
                    pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
                    search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                    strictSearch: true,
                    showColumns: true, //是否显示所有的列
                    showRefresh: true, //是否显示刷新按钮
                    minimumCountColumns: 2, //最少允许的列数
                    clickToSelect: true, //是否启用点击选中行
                    //height: 500, //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "Id", //每一行的唯一标识，一般为主键列
                    showToggle: true, //是否显示详细视图和列表视图的切换按钮
                    cardView: false, //是否显示详细视图
                    detailView: true, //是否显示父子表
                    showExport: true,                     //是否显示导出
                    exportDataType: "all",              //basic', 'all', 'selected'.
                    columns: [{
                        checkbox: true
                    }, {
                        field: 'Id',
                        align: 'center',
                        title: '序号',
                    },
                    {
                        field: 'LineName',
                        align: 'center',
                        title: app.localize('LineId')
                    },
                    
                    
                    {
                        field: 'AlcCode',
                        align: 'center',
                        title: app.localize('AlcCodeId')
                    },
                    {
                        field: 'PlanModeCode',
                        align: 'center',
                        title: app.localize('PlanModeId')
                    },
                     {
                         field: 'AfterSalePart',
                         align: 'center',
                         title: app.localize('AfterSalePart')
                     },
                    {
                        field: 'Priority',
                        align: 'center',
                        title: app.localize('Priority')
                    },
                    {
                        field: 'PlanQty',
                        align: 'center',
                        title: app.localize('PlanQty'),
                    },
                    {
                        field: 'PlanDate',
                        align: 'center',
                        title: app.localize('PlanDate'),
                        formatter: function (value, row, index) {
                            var time = row.PlanDate;
                            return moment(time).format("YYYY-MM-DD")
                        }
                    },
                    {
                        field: 'CreationTime',
                        align: 'center',
                        title: app.localize('CreationTime'),
                        formatter: function (value, row, index) {
                            var time = row.CreationTime;
                            return moment(time).format("YYYY-MM-DD HH:mm:ss")
                        }
                    },
                      {
                          field: 'Remarks',
                          align: 'center',
                          title: app.localize('Remark')
                      }, {
                        field: 'operate',
                        title: app.localize('operate'),
                        align: 'center',
                        valign: 'middle',
                        clickToSelect: false,
                        formatter: operateFormatter,
                        events: operateEvents
                    }],
                    //注册加载子表的事件。注意下这里的三个参数！                  
                    onExpandRow: function (index, row, $detail) {
                        oTableInit.InitSubTable(index, row, $detail);
                    }
                });
            };
            //指定操作组
            function operateFormatter(value, row, index) {
                var $span = '';
                $span.add
                if (_permissions.edit) {
                    $span = $span + '<a class="edit" href="javascript:void(0)" title="'
                        + app.localize('Edit') + '"><i class="glyphicon glyphicon-edit"></i></a>'
                }
                //删除
                if (_permissions.delete) {
                    $span = $span + '<a class="remove" href="javascript:void(0)" title="'
                        + app.localize('Delete') + '"><i class="glyphicon glyphicon-remove"></i></a>'
                }
                return $span;
            }

            //指定table表体操作事件
            window.operateEvents = {
                'click .edit': function (e, value, row, index) {
                    _createOrEditModal.open({ id: row.Id });
                },
                'click .remove': function (e, value, row, index) {
                    deletePlan(row);
                }
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                //alert($("#seatPositionId").val());
                var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit,   //页面大小
                    offset: params.offset,  //页码
                    sort: params.sort,  //排序列名  
                    sortOrder: params.order,//排位命令（desc，asc）  
                    lineId: $("#lineId").val(),
                    planModeId: $("#planModeId").val(),
                    planDate: $("#PlanDate").val(),
                    isOnline01: $("#isOnline01").val(),
                    isOnline02: $("#isOnline02").val(),
                    isOnline03: $("#isOnline03").val(),
                    isOnline04: $("#isOnline04").val(),
                    isOnline05: $("#isOnline05").val(),
                    isOnline06: $("#isOnline06").val(),
                    isOnline07: $("#isOnline07").val(),
                    isOnline08: $("#isOnline08").val(),
                    isOnline09: $("#isOnline09").val(),
                    isOnline10: $("#isOnline10").val(),
                    seatPositions: $("#seatPositionId").val()
                };
                return temp;
            };

            //初始化子表格(无线循环)
            oTableInit.InitSubTable = function (index, row, $detail) {
                var parentid = row.Id;
                var cur_table = $detail.html('<table></table>').find('table');
                $(cur_table).bootstrapTable({
                    url: '/PlanDetails/GetAllPlanDetailsByPlanId',
                    method: 'get',
                    striped: true,
                    cache: false,
                    pagination: true,
                    sortable: true,
                    queryParams: function (params) {
                        params.planid = parentid;
                        return params;
                    },
                    queryParamsType: "limit",
                    detailView: false,//父子表
                    sidePagination: "server",
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    search: false,
                    showColumns: false,
                    showRefresh: false,
                    minimumCountColumns: 2,
                    clickToSelect: true,
                    columns: [
                        {
                        checkbox: true
                        },
                        {
                            field: 'Id',
                            align: 'center',
                            title: app.localize('Id')
                        },
                        {
                            field: 'SeatPositionCode',
                            align: 'center',
                            title: app.localize('SeatPositionId')
                        },
                        {
                            field: 'SeatID',
                            align: 'center',
                            title: app.localize('SeatID')
                        },
                        {
                            field: 'SeatSeq',
                            align: 'center',
                            title: app.localize('SeatSeq')
                        },
                        {
                            field: 'IsOnline01',
                            align: 'center',
                            title: app.localize('IsOnline01')
                        },
                        {
                            field: 'IsOnline02',
                            align: 'center',
                            title: app.localize('IsOnline02')
                        },
                        {
                            field: 'IsOnline03',
                            align: 'center',
                            title: app.localize('IsOnline03')
                        },
                        {
                            field: 'IsOnline04',
                            align: 'center',
                            title: app.localize('IsOnline04')
                        },
                        {
                            field: 'IsOnline05',
                            align: 'center',
                            title: app.localize('IsOnline05')
                        },
                        {
                            field: 'IsOnline06',
                            align: 'center',
                            title: app.localize('IsOnline06')
                        },
                        {
                            field: 'IsOnline07',
                            align: 'center',
                            title: app.localize('IsOnline07')
                        },
                        {
                            field: 'IsOnline08',
                            align: 'center',
                            title: app.localize('IsOnline08')
                        },
                        {
                            field: 'IsOnline09',
                            align: 'center',
                            title: app.localize('IsOnline09')
                        },
                        {
                            field: 'IsOnline10',
                            align: 'center',
                            title: app.localize('IsOnline10')
                        },
                        //{
                        //    field: 'IsOnline11',
                        //    align: 'center',
                        //    title: app.localize('IsOnline11')
                        //},
                        //{
                        //    field: 'IsOnline12',
                        //    align: 'center',
                        //    title: app.localize('IsOnline12')
                        //},
                        //{
                        //    field: 'IsOnline13',
                        //    align: 'center',
                        //    title: app.localize('IsOnline13')
                        //},
                        //{
                        //    field: 'IsOnline14',
                        //    align: 'center',
                        //    title: app.localize('IsOnline14')
                        //},
                      
                        //{
                        //    field: 'IsOnline15',
                        //    align: 'center',
                        //    title: app.localize('IsOnline15')
                        //},
                        //{
                        //    field: 'IsOnline16',
                        //    align: 'center',
                        //    title: app.localize('IsOnline16')
                        //},
                        //{
                        //    field: 'IsOnline17',
                        //    align: 'center',
                        //    title: app.localize('IsOnline17')
                        //},
                        //{
                        //    field: 'IsOnline18',
                        //    align: 'center',
                        //    title: app.localize('IsOnline18')
                        //},
                        //{
                        //    field: 'IsOnline19',
                        //    align: 'center',
                        //    title: app.localize('IsOnline19')
                        //},
                        //{
                        //    field: 'IsOnline20',
                        //    align: 'center',
                        //    title: app.localize('IsOnline20')
                        //},
                    ],
                    ////无线循环取子表，直到子表里面没有记录
                    //onExpandRow: function (index, row, $Subdetail) {
                    //    oTableInit.InitSubTable(index, row, $Subdetail);
                    //}
                });
            };
            return oTableInit;
        };

        // #region CRUD按钮操作

        $("#btn-add").click(function () {
            //alert($("#seatPositionId").val()[0]);
            _createOrEditModal.open();
        });

        $("#btn-edit").click(function () {
            var selectedRaido = _$table.bootstrapTable('getSelections');
            if (selectedRaido.length === 0) {
                abp.notify.warn(app.localize('PleaseSelectForEdit'));
            } else {
                _createOrEditModal.open({ id: selectedRaido[0].Id });
            }
        });

        $("#btn-delete").click(function () {
            var selectedRaido = _$table.bootstrapTable('getSelections');
            if (selectedRaido.length === 0) {
                abp.notify.warn(app.localize('PleaseSelectForDelete'));
            } else {
                var arr = new Array();
                for (var i = 0; i < selectedRaido.length; i++) {
                    arr.push(selectedRaido[i]['Id']);
                }
                batchDelete(arr);
            }
        });
        // #endregion
        //
        //
        //删除当前plan实体
        function deletePlan(plan) {
            abp.message.confirm(
                app.localize('PlanDeleteWarningMessage', plan.PlanDate, plan.Priority),
                function (isConfirmed) {
                    if (isConfirmed) {
                        _planService.deletePlanAsync({
                            id: plan.Id
                        }).done(function () {
                            _$table.bootstrapTable('refresh');
                            abp.notify.success(app.localize('SuccessfullyDeleted'));
                        });
                    }
                }
            );
        };
        function batchDelete(obj) {
            abp.message.confirm(
                app.localize('PlanDeleteWarningMessage', obj),
                function (isConfirmed) {
                    if (isConfirmed) {
                        _planService.batchDeletePlanAsync(
                            obj
                        ).done(function () {
                            _$table.bootstrapTable('refresh');
                            abp.notify.success(app.localize('SuccessfullyDeleted'));
                        });
                    }
                }
            );
        }

        //导出为excel文档
     
        $('#btn-export').click(function () {
            layer.load(0, {
                shade: [0.3, '#000'] //0.1透明度的白色背景
            });

            _planService
                .getPlanToExcel({
                    lineId: $("#lineId").val(),
                    planModeId: $("#planModeId").val(),
                    planDate: $("#PlanDate").val(),
                    isOnline01: $("#isOnline01").val(),
                    isOnline02: $("#isOnline02").val(),
                    isOnline03: $("#isOnline03").val(),
                    isOnline04: $("#isOnline04").val(),
                    isOnline05: $("#isOnline05").val(),
                    isOnline06: $("#isOnline06").val(),
                    isOnline07: $("#isOnline07").val(),
                    isOnline08: $("#isOnline08").val(),
                    isOnline09: $("#isOnline09").val(),
                    isOnline10: $("#isOnline10").val(),
                    seatPositions: $("#seatPositionId").val()
                })
                 .done(function (result) {
                     layer.closeAll('loading');
                     app.downloadTempFile(result);
                 });
        });
        $("#btn-query").click(function () {
            _$table.bootstrapTable('refresh');
        });

        //制作Plan事件,用于请求变化后，刷新表格信息
        abp.event.on('app.createOrEditPlanModalSaved', function () {
            _$table.bootstrapTable('refresh');
        });

        var oTable = new TableInit();
        oTable.Init();
        _$table.bootstrapTable('hideColumn', 'Id');

        // 初始化 计划日期 的包含时分秒的日期控件
        //包含时分秒的日期选择器
        $("input[name=PlanDate]").datepicker({
            autoclose: true,
            isRTL: false,
            format: "yyyy-mm-dd",
            pickerPosition: ("bottom-left"),
            //默认为E文按钮要中文，自己去找语言包
            todayBtn: true,
            todayHighlight: true,
            language: "zh-CN"
        });

        //渲染select
        $("#isOnline01").selectpicker();
        $("#seatPositionId").selectpicker();
        //$("#isOnline01").append("<option value=''> </option>");
        //alert($("#isOnline").val());
        //默认为当天日期
        //$("input[name=PlanDate]").datepicker('setDate', new Date());





        var _modalManager;

        var _planService = abp.services.app.plan;

        //$(".maxlength-handler").maxlength({
        //          limitReachedClass: "label label-danger",
        //          alwaysShow: true,
        //          threshold: 5,
        //          placement: 'bottom'
        //      });

        this.init = function (modalManager) {

            //渲染select
            $("#lineIdEdit").selectpicker();

            //渲染select
            $("#alcCodeIdEdit").selectpicker();

            //渲染select
            $("#planModeIdEdit").selectpicker();

            // 初始化 计划日期 的包含时分秒的日期控件
            //包含时分秒的日期选择器
            $("input[name=PlanDate]").datepicker({
                autoclose: true,
                isRTL: false,
                format: "yyyy-mm-dd",
                pickerPosition: ("bottom-left"),
                //默认为E文按钮要中文，自己去找语言包
                todayBtn: true,
                todayHighlight: true,
                language: "zh-CN"
            });
        }

        //下拉框二级联动
        $("#lineIdEdit").change(function () {
            //获取线体的ID
            var lineID = $("#lineIdEdit").val();
            //获取线体
            var lst = $("#alcCodeIdEdit");
            $.ajax({
                type: "get",
                url: "/LineAlcCodes/GetAllAlcCodesByLineId",
                data: { id: lineID },
                dataType: 'JSON', //返回数据的格式
                contentType: 'application/json',
                success: function (data, status) {
                    if (status == "success") {
                        lst.empty();//清空下拉框
                        $.each(data, function (i, item) {
                            lst.append("<option value='" + data[i].Value + "'>" + data[i].DisplayText + "</option>");
                        });
                        lst.selectpicker('refresh');
                    }
                },
                error: function () {
                    toastr.error('Error');
                },
            });
        });

        $("#btn-save").click(function () {
            var plan = $('#planInformationsForm').serializeFormToObject();

            _planService.createOrUpdatePlanAsync({
                planEditDto: plan
            }).done(function () {
                //提示信息
                abp.notify.info(app.localize('SavedSuccessfully'));
                ////信息保存成功后调用事件，刷新列表
                abp.event.trigger('app.createOrEditPlanModalSaved');
            });
        });
    });
})();